﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using GeneralDFS.BusinessLogical.Config;
using GeneralDFS.BusinessLogical.Nodes;
using GeneralDFS.Common;
using GeneralDFS.Common.Network;
using GeneralDFS.BusinessLogical.Network;
using GeneralDFS.DataEntity.Config;
using GeneralDFS.DataEntity.IO;
using GeneralDFS.DataEntity.Nodes;
using GeneralDFS.DataEntity.Enum;

namespace GeneralDFS.BusinessLogical.RemoteObject
{
    public class DataNodeRemoteObject : MarshalByRefObject
    {
        private DataNodeConfig dataNodeConfig;
        private DataNode dataNode;

        public int Port { get { return dataNode.DataNodeInfo.RpcPort; } }

        public DataNodeRemoteObject(DataNode dataNode)
        {
            this.dataNode = dataNode;
            this.dataNodeConfig = dataNode.GetNodeConfig();
        }

        #region old method
        //public int OpenNewTcpConnection(TcpConnectionType.TcpOpenType tcpOpenType)
        //{
        //    var port = PortHelper.GetFirstAvailablePort();
        //    if (tcpOpenType == TcpConnectionType.TcpOpenType.SendBlock)
        //    {
        //        LogUtil.LogInfo("the thread of the connection used to sendBlock initing");
        //        var socket = new AsyncDataNodeTcpListener((new ConfigCenter()).GetConfig(),IPAddress.Parse(dataNodeConfig.Ip), port);
        //        socket.ChangeToSelf(dataNode,dataNodeConfig);
        //        var thread = new Thread(socket.Read);
        //        thread.Start();
        //        LogUtil.LogInfo(String.Format("thread init success and start at {0}",port));
        //    }
        //    return port;
        //}

        //public Boolean RequestBlock(String ip,int port,Guid fileBlockName)
        //{
        //    string filePath = FSVolume.GetInstance().GetFilePath(fileBlockName);
        //    if (filePath != null)
        //    {
        //        if (System.IO.File.Exists(filePath) && System.IO.File.Exists(filePath + ".meta"))
        //        {
        //            var metaData =
        //                SerializeHelper.GetModel(System.IO.File.OpenRead(filePath + ".meta")) as FileBlockMetaData;
        //            var socket = new AsyncDataNodeTcpClient((new ConfigCenter()).GetConfig(), ip, port);
        //            socket.Write(metaData, System.IO.File.OpenRead(filePath));
        //            return true;
        //        }
        //    }
        //    return false;
        //}

        #endregion

        public void Shutdown()
        {
            GeneralDFS.BusinessLogical.Shutdown.PowerOff();
        }

        public void Reboot()
        {
            GeneralDFS.BusinessLogical.Shutdown.Reboot();
        }

        public void LogoOff()
        {
            GeneralDFS.BusinessLogical.Shutdown.LogoOff();
        }
    }
}